/**
 * 时间格式化工具函数
 */

/**
 * 格式化日期
 * @param {Date|String|Number} time 日期对象/时间戳/日期字符串
 * @param {String} format 格式化模板，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {String} 格式化后的时间字符串
 */
export function formatDate(time, format = 'YYYY-MM-DD') {
  if (!time) return '';
  
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  
  const formatObj = {
    YYYY: date.getFullYear(),
    MM: date.getMonth() + 1,
    DD: date.getDate(),
    HH: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds(),
    W: date.getDay()
  };
  
  return format.replace(/(YYYY|MM|DD|HH|mm|ss|W)/g, (match) => {
    let val = formatObj[match];
    if (match === 'W') {
      return ['日', '一', '二', '三', '四', '五', '六'][val];
    }
    if (val < 10) {
      val = '0' + val;
    }
    return val;
  });
}

/**
 * 获取相对时间
 * @param {Date|String|Number} time 日期对象/时间戳/日期字符串
 * @returns {String} 相对时间字符串，如"刚刚"、"1小时前"等
 */
export function getRelativeTime(time) {
  if (!time) return '';
  
  const now = new Date().getTime();
  let date;
  
  if (typeof time === 'object') {
    date = time.getTime();
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time).getTime();
  }
  
  const diff = (now - date) / 1000;
  
  if (diff < 60) {
    return '刚刚';
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + '分钟前';
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + '小时前';
  } else if (diff < 604800) {
    return Math.floor(diff / 86400) + '天前';
  } else {
    return formatDate(time, 'MM-DD');
  }
}
